package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取本次url
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", requestURI);
        String[] urls = new String[]{
                "/employee/login", "/employee/logout", "/backend/**", "/front/**", "/user/login",
                "/user/sendMsg"
        };
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) { //路径匹配成功   放行
                log.info("路径匹配成功,路径为：{}", requestURI);
                filterChain.doFilter(request, response);
                return;
            }
        }
        //是否登录
        Employee emp = (Employee) request.getSession().getAttribute("employee");
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        if (emp != null || loginUser != null) {
            log.info("已登录，用户名：{}", emp);
            //获取session中存储的id放入线程中
            if (emp != null) {
                //设置后台登录id
                Long empId = emp.getId();
                BaseContext.setCurrentId(empId);
            }
            if (loginUser != null) {

                Long userId = loginUser.getId();
                log.info("移动端已登录，用户名：{}", userId);
                BaseContext.setCurrentId(userId);
            }
            //放行
            filterChain.doFilter(request, response);
            //释放存储的id  防止内存溢出
            BaseContext.release();
        } else {
            //未登录  响应json
            log.info("未登录");
            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        }
    }
}
